package com.gkzf.ai.module.crm.config;

import com.gkzf.ai.framework.common.exception.ServiceException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class RepeatSubmitAspect {

    private static final long TIME_INTERVAL = 5; // 5秒内不可重复提交

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Around("@annotation(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (attributes != null) {
            request = attributes.getRequest();
        }

        String token = null; // 或者从前端传入 requestId
        if (request != null) {
            token = request.getHeader("Authorization");
        }
        String key = "repeat_submit:" +noRepeatSubmit.value()+":"+ token;

        String existing = redisTemplate.opsForValue().get(key);
        if (existing != null) {
            throw new ServiceException(429,"请勿重复提交");
        }

        redisTemplate.opsForValue().set(key, "1", TIME_INTERVAL, TimeUnit.SECONDS);

        return joinPoint.proceed();
    }
}